package com.example.grpcservice;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;

public class HelloClient {

    private ManagedChannel channel;
    private GreeterGrpc.GreeterBlockingStub blockingStub;

    public HelloClient(){
        channel = ManagedChannelBuilder.forAddress("127.0.0.1", 8082)
                .usePlaintext()
                .build();

        blockingStub = GreeterGrpc.newBlockingStub(channel);
    }

    private void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    public void greet(String name) {

        HelloRequest helloRequest = HelloRequest.newBuilder().setName(name).build();
        HelloReply helloReply;

        helloReply = blockingStub.sayHello(helloRequest);

        System.out.println("Message from gRPC-Server: "+helloReply.getMessage());

    }

    public static void main(String[] args) throws InterruptedException {
        HelloClient helloClient = new HelloClient();
        String user = "baohuajie";
        try {
            helloClient.greet(user);
        } finally {
            helloClient.shutdown();
        }
    }

}
